<template>
  <div class="showTheLogin">
    <Title
      :status="accountForm.isRegistered"
      @registered="registered"
    />
    <el-form
      ref="formRef"
      :model="accountForm"
      :rules="rules"
    >
      <el-form-item prop="userName">
        <el-input
          v-model="accountForm.userName"
          maxlength="11"
          placeholder="请输入您的手机号码"
        >
          <template #prepend>
            <span class="icon iconfont">&#xe62f;</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="graphicCode" class="graphicCode">
        <el-input
            v-model="accountForm.graphicCode"
            maxlength="6"
            placeholder="请输入图形验证码"
            @keyup.enter="login"
        >
          <template #prepend>
            <span class="icon iconfont">&#xe62e;</span>
          </template>
          <template #append>
            <img v-if="captcha" :src="captcha" @click="loadImage" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="verificationCode">
        <el-input
          v-model="accountForm.verificationCode"
          maxlength="6"
          placeholder="请输入验证码"
          @keyup.enter="login"
        >
          <template #prepend>
            <span class="icon iconfont">&#xe62e;</span>
          </template>
          <template #append>
            <span
              class="codeBtn"
              v-show="accountFormSetting.visibleGetCode"
              @click="getCode"
            >获取验证码</span>
            <span
              v-show="!accountFormSetting.visibleGetCode"
              class="codeBtn codeCount"
            >重新获取({{ accountFormSetting.codeCountNum }}s)</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item
        v-if="accountForm.isRegistered === 1"
        prop="haveRead"
      >
        <el-checkbox
          v-model="accountForm.haveRead"
          style="margin: 0 12px 0 0; "
        />
        <span>已阅读并同意</span>
        <span
          class="hightLight pointer"
          @click="readAgreement"
        >
          《cereshop 服务协议》
        </span>
      </el-form-item>
      <el-form-item
        v-show="accountForm.isRegistered === 2"
      >
        <el-checkbox
          v-model="accountForm.isAutoLogin"
        >七天免登录</el-checkbox>
      </el-form-item>
      <el-button
        class="loginBtn"
        :loading="accountFormSetting.loadingLogin"
        @click="loginSubmit"
      >
        {{
          accountForm.isRegistered === 1
            ? '立即注册'
            : '立即登录'
        }}
      </el-button>
    </el-form>
    <el-dialog
      title="服务协议"
      v-model="accountFormSetting.dialogAgreement"
      width="50%"
    >
      这是服务协议
    </el-dialog>
  </div>
</template>

<script setup>
import Cookie from 'js-cookie'
import {
  getTheCode,
  login
} from '@/api/login.js'
import {
  getUserInfo
} from '@/api/user/user.js'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useUser } from '@/store/user'
import Title from './title.vue'
import {uploadURL} from "@/util/server";

defineComponent({
  name: 'LoginIndex',
})

/**
 * accountForm
 * @namespace
 * @description 登录表单
 * @property {string} userName 账户
 * @property {string} verificationCode 验证码
 * @property {string} isRegistered 1 注册
 * @property {boolean} haveRead 是否阅读服务协议
 * @property {boolean} isAutoLogin 是否7天免登录
 */
const accountForm = reactive({
  userName: '',
  verificationCode: '',
  isRegistered: 2,
  haveRead: false,
  isAutoLogin: false,
  graphicCode: ''
});
const captcha = ref('')
const userStore = useUser()
const formRef = ref();
const rules = {
  userName: [
    { validator: validateUserName, trigger: 'blur' },
  ],
  graphicCode: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' },
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
  haveRead: [
    { validator: validateBoolean, trigger: 'change' },
  ],
}
function loadImage () {
  captcha.value = uploadURL + '/code/captcha' + '?' + Math.random()
}
function validateUserName (rule, value, callback) {
  if (value === '') {
    return callback(new Error('请输入您的手机号'))
  }
  if (!/^1[13456789]\d{9}$/.test(value)) {
    return callback(new Error('手机号格式错误'))
  }
  callback()
}
function validateBoolean (rule, value, callback) {
  if (!value) {
    return callback(new Error('请阅读服务协议'))
  }
  callback()
}
/**
 * 登录表单 相关配置
 * @property {boolean} loadingLogin
 * @property {string} verificationCode 验证码
 * @property {string} userName
 */
const accountFormSetting = reactive({
  loadingLogin: false,
  visibleGetCode: true, // 验证码获取cd
  codeCountNum: 0, // 验证码获取倒计时
  dialogAgreement: false, // 服务协议
})
const timer = ref(null);

// function getUserInfoData () {
//   getUserInfo().then(response => {
//     const res = response.data
//     if (res.code === '200') {
//       userStore.setUserInfo(res.data)
//     }
//   })
// }

function getCode () {
  const TIME_COUNT = 120;
  let reg = /^1[13456789]\d{9}$/;
  if (!reg.test(accountForm.userName)) {
    ElMessage({
      message: '手机号格式错误',
      type: 'error',
      customClass: 'messageZindex',
    })
    return
  }
  if (accountForm.graphicCode.value === '') {
    ElMessage({
      message: '请先输入图形验证码',
      type: 'error',
      customClass: 'messageZindex',
    })
    return
  }
  getTheCode({
    code: accountForm.graphicCode,
    phone: accountForm.userName
  }).then(response => {
    accountFormSetting.codeCountNum = TIME_COUNT
    accountFormSetting.visibleGetCode = false
    timer.value = setInterval(() => {
      if (
        accountFormSetting.codeCountNum > 0
          && accountFormSetting.codeCountNum <= TIME_COUNT
      ) {
        accountFormSetting.codeCountNum--
      } else {
        accountFormSetting.visibleGetCode = true
        clearInterval(timer.value)
        timer.value = null
      }
    }, 1000)
    // const res = response.data
    // if (res.code === '200') {
    //   if (!timer.value) {
    //     accountFormSetting.codeCountNum = TIME_COUNT
    //     accountFormSetting.visibleGetCode = false
    //     timer.value = setInterval(() => {
    //       if (
    //         accountFormSetting.codeCountNum > 0
    //       && accountFormSetting.codeCountNum <= TIME_COUNT
    //       ) {
    //         accountFormSetting.codeCountNum--
    //       } else {
    //         accountFormSetting.visibleGetCode = true
    //         clearInterval(timer.value)
    //         timer.value = null
    //       }
    //     }, 1000)
    //   }
    //   ElMessage({
    //     message: '验证码获取成功',
    //     type: 'success',
    //     customClass: 'messageZindex'
    //   })
    // } else {
    //   ElMessage({
    //     message: res.message,
    //     type: 'warning',
    //     customClass: 'messageZindex'
    //   })
    // }
  })
}

function readAgreement () {
  accountFormSetting.dialogAgreement = true
}
function loginSubmit () {
  formRef.value.validate(valid => {
    if (valid) {
      accountFormSetting.loadingLogin = true
      login({
        phone: accountForm.userName,
        verificationCode: accountForm.verificationCode,
        type: accountForm.isRegistered,
        terminal: 5
      }).then(response => {
        const res = response.data
        if (res.code === '200') {
          Cookie.set(
            'token',
            res.data.token,
            {
              expires: accountForm.isAutoLogin ? 7 : 1
            }
          )
          // getUserInfoData();
          ElMessage({
            message: '登录成功',
            type: 'success',
            customClass: 'messageZindex'
          })
          userStore.setShowLogin()
          userStore.setIsLogin(true)
          location.reload()
        } else {
          ElMessage({
            message: res.message,
            type: 'warning',
            customClass: 'messageZindex'
          })
        }
      }).catch(err => { console.log(err) })
        .finally(() => {
          accountFormSetting.loadingLogin = false
        })
    }
  })
}


function registered () {
  formRef.value.resetFields();
  accountFormSetting.visibleGetCode = true
  clearInterval(timer.value)
  timer.value = null
  accountForm.userName = ''
  accountForm.verificationCode = ''
  accountForm.graphicCode = ''
  accountForm.isRegistered = accountForm.isRegistered === 1 ? 2 : 1
}

onMounted(() => {
  captcha.value = uploadURL + '/code/captcha'
})
</script>

<style lang="scss" scoped>
// 登录提示语层级
.messageZindex {
  z-index: 9999 !important;
}
.showTheLogin {
  width: 100%;
  height: 100%;
  .hightLight{
    color: $mainGlod;
  }
  .el-input{
    height: 50px;
    background: $mainGlod;
    border-radius: 4px;
  }
  .codeBtn {
    // background-color: $mainGlod;
  //   border-radius: 0;
  //   text-align: center;
    cursor: pointer;
  }
  // .codeCount {
  //   color: #999999;
  // }
  .loginBtn {
    width: 100%;
    height: 70px;
    color: $mainGlod;
    background: #333333;
    border-radius: 0;
    border: 1px solid #333333;
    text-align: center;
    font-size: 20px;
    cursor: pointer;
    &:hover{
      color: #FFF;
      background-color: $mainGlod;
      border: 1px solid $mainGlod;
    }
  }
  :deep(.el-checkbox__inner){
    width: 20px;
    height: 20px;
    &:after {
      height: 10px;
      left: 7px;
      width: 4px;
    }
  }
  :deep(.el-dialog__body){
    max-height: 500px;
    min-height: 300px;
    overflow: auto;
  }
  :deep(.graphicCode) {
    img {
      width: 109px;
    }
    .el-input-group__append {
      padding: 1px;
      background: #fff;
    }
  }
}
</style>
